<template>
  <van-field
    :label="titleText(options, item)"
    :name="item.itemTitle"
    :required="item.isRequired === 'Y'"
    :rules="[
      { required: item.isRequired === 'Y', message: '请选择' + item.itemTitle },
    ]"
    label-width="33rem"
  >
    <template #input>
      <p v-if="options.showDesc" class="desc f12 mb10">
        {{ options.description }}
      </p>
      <div>
        <div
          v-for="(next, idx) in options.optionItems"
          :key="next.label"
          class="w30 mt15"
        >
          <p v-if="options.optionItems.length > 1" class="mb10">
            {{ next.label }}
          </p>
          <Slider
            v-model="item.value[idx]"
            :disabled="type === 'view'"
            :max="max"
            :min="min"
            @change="onChange(idx)"
          >
            <template #button>
              <div class="custom-button">
                {{
                  item.value[idx] ||
                  (options.sliderSet.limitValue ? options.sliderSet.min : 0)
                }}
              </div>
            </template>
          </Slider>
          <p class="flb">
            <span class="f12">{{ options.sliderSet.minText }}</span>
            <span class="f12">{{ options.sliderSet.maxText }}</span>
          </p>
        </div>
      </div>
    </template>
  </van-field>
</template>

<script setup>
import { titleText } from "@/utils/common.js";
import { showNotify, Slider } from "vant";
import { onBeforeMount, onMounted, ref, } from "vue";

//defineOptions({ name: "H5Slider" });

const { item, type } = defineProps(["item", "type"]);
const emits = defineEmits(["change"]);

const { options } = JSON.parse(item.vformJson);
let min = ref(0);
let max = ref(100);
// 传递值改变后
const onChange = (idx) => {
  let sum = eval(item.value.join("+"));
  if (options.sliderSet.limitTotal && sum > options.sliderSet.total) {
    showNotify({
      type: "danger",
      message: "总和不能超过" + options.sliderSet.total,
    });
    item.value[idx] = 0;
  }
  emits("change", item);
};
onBeforeMount(() => {
  if (!item.value) {
    item.value = [];
  }
});
// 挂载后运行
onMounted(() => {
  if (options.sliderSet.limitValue) {
    min.value = options.sliderSet.min || 0;
    max.value = options.sliderSet.max || 100;
  }
  let sum = eval(item.value.join("+"));
  if (!sum) item.value = options.optionItems.map(() => 0); // 填写的时候
});
</script>

<style lang="less" scoped>
.custom-button {
  width: 26px;
  color: #fff;
  font-size: 10px;
  line-height: 18px;
  text-align: center;
  background-color: var(--van-primary-color);
  border-radius: 100px;
}
</style>